import React, { useState } from 'react';
import { Input } from 'antd';
import { EditOutlined, CheckOutlined, CloseOutlined } from '@ant-design/icons';
import './index.less';

interface PROPS {
    value: string;
    onConfirm: (value: string) => Promise<any>;
}

export default (props: PROPS) => {
    const { value, onConfirm } = props;
    const [editable, setEditable] = useState(false);
    const [inputValue, setInputValue] = useState(value);

    const confirm = () => {
        onConfirm(inputValue)
            .then(() => setEditable(false))
            .catch(() => setEditable(true));
    };

    return editable ? (
        <div className="container">
            <Input className="mr5" defaultValue={value} onPressEnter={confirm} onChange={(e) => setInputValue(e.target.value)} allowClear></Input>
            <CheckOutlined className="mr5" onClick={confirm}></CheckOutlined>
            <CloseOutlined onClick={() => setEditable(false)} />
        </div>
    ) : (
        <div className="container">
            <span className="mr5">{value}</span>
            <EditOutlined onClick={() => setEditable(true)}></EditOutlined>
        </div>
    );
};
